<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <el-col :span="8">
        <!-- 个人信息卡片 -->
        <el-card class="profile-card">
          <div class="profile-header">
            <el-avatar :size="80" :src="userInfo?.avatar">
              {{ userInfo?.nickname?.charAt(0) || userInfo?.username?.charAt(0) }}
            </el-avatar>
            <div class="profile-info">
              <h3>{{ userInfo?.nickname || userInfo?.username }}</h3>
              <p class="username">@{{ userInfo?.username }}</p>
              <el-tag :type="userInfo?.status === 1 ? 'success' : 'danger'" size="small">
                {{ userInfo?.status === 1 ? '正常' : '禁用' }}
              </el-tag>
            </div>
          </div>
          
          <el-divider />
          
          <div class="profile-stats">
            <div class="stat-item">
              <span class="label">最后登录时间</span>
              <span class="value">{{ formatDate(userInfo?.loginTime) }}</span>
            </div>
          </div>
          
          <el-divider />
          
          <div class="profile-actions">
            <el-button type="primary" @click="showEditProfile = true">
              编辑资料
            </el-button>
            <el-button @click="showChangePassword = true">
              修改密码
            </el-button>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="16">
        <el-tabs v-model="activeTab">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="info">
            <el-card>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="用户名">{{ userInfo?.username }}</el-descriptions-item>
                <el-descriptions-item label="昵称">{{ userInfo?.nickname }}</el-descriptions-item>
                <el-descriptions-item label="邮箱">{{ userInfo?.email || '未设置' }}</el-descriptions-item>
                <el-descriptions-item label="手机号">{{ userInfo?.phone || '未设置' }}</el-descriptions-item>
                <el-descriptions-item label="状态">
                  <el-tag :type="userInfo?.status === 1 ? 'success' : 'danger'">
                    {{ userInfo?.status === 1 ? '正常' : '禁用' }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="最后登录">{{ formatDate(userInfo?.loginTime) }}</el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-tab-pane>
          
          <!-- 操作日志 -->
          <el-tab-pane label="操作日志" name="logs">
            <el-card>
              <div v-loading="logLoading">
                <el-timeline v-if="operationLogs.length > 0">
                  <el-timeline-item
                    v-for="log in operationLogs"
                    :key="log.id"
                    :timestamp="formatDate(log.createdTime)"
                    placement="top"
                  >
                    <el-card class="log-item">
                      <div class="log-content">
                        <div class="log-operation">
                          <el-tag :type="log.status === 1 ? 'success' : 'danger'" size="small">
                            {{ log.operation }}
                          </el-tag>
                        </div>
                        <div class="log-details">
                          <p><strong>请求方法:</strong> {{ log.method }}</p>
                          <p><strong>IP地址:</strong> {{ log.ip }}</p>
                          <p><strong>执行时间:</strong> {{ log.executionTime }}ms</p>
                          <p v-if="log.errorMsg" class="error-msg">
                            <strong>错误信息:</strong> {{ log.errorMsg }}
                          </p>
                        </div>
                      </div>
                    </el-card>
                  </el-timeline-item>
                </el-timeline>
                <el-empty v-else description="暂无操作日志" />
              </div>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    
    <!-- 编辑资料弹窗 -->
    <el-dialog v-model="showEditProfile" title="编辑个人资料" width="500px">
      <el-form ref="profileFormRef" :model="profileForm" :rules="profileRules" label-width="80px">
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="profileForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profileForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="profileForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="头像">
          <el-input v-model="profileForm.avatar" placeholder="请输入头像URL" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showEditProfile = false">取消</el-button>
        <el-button type="primary" :loading="profileLoading" @click="handleUpdateProfile">
          保存
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 修改密码弹窗 -->
    <el-dialog v-model="showChangePassword" title="修改密码" width="400px">
      <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="80px">
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请确认新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showChangePassword = false">取消</el-button>
        <el-button type="primary" :loading="passwordLoading" @click="handleChangePassword">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { profileApi } from '@/api/profile'
import { useAuthStore } from '@/store/modules/auth'
import dayjs from 'dayjs'

const authStore = useAuthStore()

const activeTab = ref('info')
const showEditProfile = ref(false)
const showChangePassword = ref(false)
const profileLoading = ref(false)
const passwordLoading = ref(false)
const logLoading = ref(false)

const userInfo = ref(null)
const operationLogs = ref([])

const profileFormRef = ref()
const passwordFormRef = ref()

const profileForm = reactive({
  nickname: '',
  email: '',
  phone: '',
  avatar: ''
})

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const profileRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

const formatDate = (date) => {
  if (!date) return '未知'
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

const loadUserProfile = async () => {
  try {
    const profile = await profileApi.getCurrentUserProfile()
    userInfo.value = profile
    
    // 初始化表单数据
    Object.assign(profileForm, {
      nickname: profile.nickname || '',
      email: profile.email || '',
      phone: profile.phone || '',
      avatar: profile.avatar || ''
    })
  } catch (error) {
    console.error('加载个人信息失败:', error)
  }
}

const loadOperationLogs = async () => {
  try {
    logLoading.value = true
    const logs = await profileApi.getMyOperationLogs(20)
    operationLogs.value = logs || []
  } catch (error) {
    console.error('加载操作日志失败:', error)
  } finally {
    logLoading.value = false
  }
}

const handleUpdateProfile = async () => {
  try {
    await profileFormRef.value.validate()
    
    profileLoading.value = true
    const updatedProfile = await profileApi.updateProfile(profileForm)
    
    userInfo.value = updatedProfile
    authStore.setUserInfo(updatedProfile)
    
    ElMessage.success('个人资料更新成功')
    showEditProfile.value = false
  } catch (error) {
    console.error('更新个人资料失败:', error)
  } finally {
    profileLoading.value = false
  }
}

const handleChangePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    
    passwordLoading.value = true
    await profileApi.changePassword(passwordForm)
    
    ElMessage.success('密码修改成功')
    showChangePassword.value = false
    
    // 重置表单
    Object.assign(passwordForm, {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
  } catch (error) {
    console.error('修改密码失败:', error)
  } finally {
    passwordLoading.value = false
  }
}

onMounted(() => {
  loadUserProfile()
  loadOperationLogs()
})
</script>

<style scoped lang="scss">
.profile-container {
  padding: 20px;
}

.profile-card {
  .profile-header {
    display: flex;
    align-items: center;
    gap: 16px;
    
    .profile-info {
      h3 {
        margin: 0 0 8px 0;
        color: #303133;
      }
      
      .username {
        margin: 0 0 8px 0;
        color: #909399;
        font-size: 14px;
      }
    }
  }
  
  .profile-stats {
    .stat-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 0;
      
      .label {
        color: #909399;
        font-size: 14px;
      }
      
      .value {
        color: #303133;
        font-weight: 500;
      }
    }
  }
  
  .profile-actions {
    display: flex;
    gap: 12px;
  }
}

.log-item {
  margin: 8px 0;
  
  .log-content {
    .log-operation {
      margin-bottom: 8px;
    }
    
    .log-details {
      p {
        margin: 4px 0;
        font-size: 14px;
        color: #606266;
        
        &.error-msg {
          color: #f56c6c;
        }
      }
    }
  }
}
</style>